package cn.apotato.inclusion.commin.regex;

import org.springframework.util.StringUtils;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author xphu
 * @version 1.0
 * @date 2021/9/1 11:58
 */
public class DateTimeRegex {
    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static final String YYYYMMDD = "yyyyMMdd";
    private static final String REGEX_YYYY_MM_DD_HH_MM_SS = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s((([0-1][0-9])|(2?[0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$";
    private static final String REGEX_YYYYMMDD = "^((\\d{3}[1-9]|\\d{2}[1-9]\\d|\\d[1-9]\\d{2}|[1-9]\\d{3})(((0[13578]|1[02])(0[1-9]|[12]\\d|3[01]))|((0[469]|11)(0[1-9]|[12]\\d|30))|(02(0[1-9]|[1]\\d|2[0-8]))))|(((\\d{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229)?$";

    public static final Map<String, String> REGEX_MAP;
    static {
        REGEX_MAP = new LinkedHashMap<>();
        REGEX_MAP.put(YYYY_MM_DD_HH_MM_SS, REGEX_YYYY_MM_DD_HH_MM_SS);
        REGEX_MAP.put(YYYYMMDD, REGEX_YYYYMMDD);
    }

    /**
     * 判断输入的字符串是否满足时间格式 ： yyyy-MM-dd HH:mm:ss
     * @param patternString 需要验证的字符串
     * @param regex 时间格式， 默认：yyyy-MM-dd HH:mm:ss
     * @return 合法返回 true ; 不合法返回false
     */
    public static boolean isTimeLegal(String patternString, String regex) {
        Pattern a=Pattern.compile(StringUtils.isEmpty(regex) ? REGEX_YYYY_MM_DD_HH_MM_SS : REGEX_MAP.get(regex));
        Matcher b=a.matcher(patternString);
        if(b.matches()) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        System.out.println(DateTimeRegex.isTimeLegal("20210901", DateTimeRegex.YYYYMMDD));
    }
}
